﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; 
using System.IO.Compression;
using System.Web.Mvc;

namespace MShop.Web.Mvc.Filters
{

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,Inherited=true, AllowMultiple=false)]
    public class CompressFilterAttribute :  FilterAttribute,System.Web.Mvc.IActionFilter
    {
        #region IActionFilter Members

        public void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext)
        {

        }

        public void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];
            if (string.IsNullOrEmpty(acceptEncoding))
                return;

            acceptEncoding = acceptEncoding.ToLowerInvariant();

            HttpResponseBase response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("gzip"))
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("deflate"))
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }

        #endregion
    }
}